﻿using AppDataStruct;
using ComLib;
using ComLib.ComType;
using EECMISWS;
using FTPService;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json.Linq;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageQueryPeopleInfo : PageControlBase
    {
        private string BaseDirectory
        {
            get
            {
                return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6), "..", ".."));  //向上两级到软件根目录
            }
        }

        private bool _bCancellFlag = false;
        //private Stopwatch sw = new Stopwatch();

        private SFZInfo _sfz = new SFZInfo();

        private bool _queryResult = false;

        private PreApplyInfo _appInfo = null;

        private WebDataAccess _webAccess = null;

        private PictureBox pictureBox1 = null;

        private Image imgQuerying = null;

        private Image imgQueryFailed = null;

        private Label labelInputTip = null;

        public PageQueryPeopleInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessQueryPeopleInfo.Instance);
        }

        /// <summary>
        /// 保存身份证信息，用于预受理
        /// </summary>
        private void SetSFZData()
        {
            IDCardAll cardInfo = Process.GetValue<IDCardAll>("IDCardInfo");
            //_sfz = new ();
            if (null != cardInfo)
            {
                _sfz.Address = cardInfo.address;
                _sfz.BirthDate = cardInfo.birthday;
                _sfz.ExpiryDate = cardInfo.validtermOfStart + "-" + cardInfo.validtermOfEnd;
                _sfz.HeaderPicturePath = cardInfo.HeadImage;
                _sfz.IsManualInputNumberVerify = cardInfo.IsManualInputNumberVerify;
                _sfz.IssueUnit = cardInfo.signdate;
                _sfz.Name = cardInfo.name;
                _sfz.Nation = cardInfo.people;
                _sfz.Sex = cardInfo.sex;
                _sfz.SFZH = cardInfo.number;
            }

            Process.SetValue("SFZInfo", _sfz);
        }

        private void GetControls()
        {
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            imgQueryFailed = GetImage("QueryFailed");
            imgQuerying = GetImage("Querying");
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            //labelInputTip.Text = "正在查询中";
            //labelInputTip.ForeColor = Color.White;
            _bCancellFlag = false;
            pictureBox1.Image = imgQuerying;
            _webAccess = WebDataAccess.Instance;
            _appInfo = new PreApplyInfo();
            _queryResult = false;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");
            //将身份证的扫描照片复制到applyinfo

            if (UserAction == UserApplyAction.TakePhotoAndWeiYinTB
               || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                SetSFZData();
                _appInfo.XCRX = Process.GetValue<string>("Liveportrait");
                _appInfo.ZZZPPATH = Process.GetValue<string>("ZZZPPath");
            }
            if (_sfz != null)
            {
                _appInfo.SFZH = _sfz.SFZH;
                _appInfo.ZWXM = _sfz.Name;
                _appInfo.CSRQ = _sfz.BirthDate;
                _appInfo.XB.Code = (_sfz.Sex == "男" ? "1" : "2");
            }

            IDCardAll cardInfo = Process.GetValue<IDCardAll>("IDCardInfo");
            if (cardInfo != null)
            {
                _appInfo.SFZZM = cardInfo.FrontImage;
                _appInfo.SFZBM = cardInfo.BackImage;
                Log.WriteAsync($"设置身份证图片：{_appInfo.SFZZM}，{_appInfo.SFZBM}");
            }

        }

        private void SetTips(string content, bool isSuccess = true)
        {
            labelInputTip.Text = content;
            int w = labelInputTip.Width;
            int x = (this.Width - w) / 2;
            labelInputTip.Left = x;
            if (!isSuccess)
            {
                labelInputTip.ForeColor = Color.Red;
            }
            else
            {
                labelInputTip.ForeColor = Color.White;
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Process.SetValue("SFZInfo", _sfz);
            Process.SetValue("PreApplyInfo", _appInfo);
            if (!Process.ContainsKey("PersonDataDirectory"))
            {
                string personDir = _config.OutputDirs[_appInfo.SFZH];
                Process.SetValue("PersonDataDirectory", personDir);
            }
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _queryResult = false;
            _appInfo = null;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            if (IsMainPage)
            {
                BeginQuerying();
            }
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnNext_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            StopCountdown();
            _bCancellFlag = true;
            AbortWork();
            base.btnCancel_Click(sender, e);
        }

        private void InitBaseButtons()
        {
            if (UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || UserAction == UserApplyAction.OnlyWeiYinTB
                || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                buttonCancel.Visible = false;
                buttonNext.Visible = false;
                buttonBack.Visible = false;
            }
            //else
            //{
            //    buttonHome.Visible = true;
            //    buttonNext.Visible = true;
            //    buttonLast.Visible = true;
            //}
        }

        private void BeginQuerying()
        {
            if (_sfz == null)
            {
                StopCountdown();
                MessageBox.Show("无有效的身份证信息.");
                return;
            }
            WebDataAccess webAccess = WebDataAccess.Instance;
            if (!webAccess.Enabled)
            {
                //string str = BaseDirectory;
                //测试代码
                //_appInfo = new PreApplyInfo();
                CodeMap code1 = new CodeMap();
                CodeMap code3 = new CodeMap();
                CodeMap code4 = new CodeMap();
                CodeMap code5 = new CodeMap();
                CodeMap code6 = new CodeMap();
                _appInfo.ZWX = "绿";
                _appInfo.ZWM = "三洋";
                _appInfo.CSRQ = "1999-03-05";
                code1.Value = "汉族";
                code3.Value = "男";
                code4.Value = "广东省";
                code5.Value = "教师";
                code6.Value = "广东深圳市";
                code6.Code = "4400";
                _appInfo.MZ = code1;
                _appInfo.XB = code3;
                _appInfo.CSD = code4;
                _appInfo.ZY = code5;
                _appInfo.HKSZD = code6;
                _appInfo.JJLXDH = "13511111111";
                _appInfo.JJLXR = "李四";
                _appInfo.LXDH = "13540252051";
                _appInfo.SFZH = "4322341199903052312";
                _appInfo.XCRX = null;
                _appInfo.HZSQ.ZJHM = "G12345678";
                _appInfo.HZSQ.ZJYXQZ = "20101111";
                _appInfo.SCZSQ.ZJHM = "W12377777";
                _appInfo.SCZSQ.ZJYXQZ = "20221212";

                //_sfz = new SFZInfo();
                _sfz.Name = "绿三洋";
                _sfz.ExpiryDate = "2033-11-11";
                _sfz.IsManualInputNumberVerify = false;
                _sfz.BirthDate = "1985-10-31";
                _sfz.Sex = "男";
                _sfz.Sex_Code = "1";
                _sfz.Nation = "汉";
                _sfz.Nation_Code = "01";
                _sfz.SFZH = "440782198510310019";

                Process.SetValue("SFZInfo", _sfz);
                Process.SetValue("PreApplyInfo", _appInfo);
                //////////////
                StopCountdown();
                MessageBox.Show("全国版接口未启用.");
                Process.ToNext();
                return;
            }
            Task.Factory.StartNew(() =>
            {
                //先通过FTP查找照片
                QueryPeopleInfo();
                //if (GetPhoto())
                //{
                //    QueryPeopleInfo();
                //}
                //else
                //{
                //    if (CheckGoNext())
                //    {
                //        QueryPeopleInfo();
                //    }
                //    else
                //    {
                //        Action handler = () =>
                //        {                         
                //            CountdownSecond = 5;
                //            StartCountdown();
                //        };
                //        this.Invoke(handler);
                //    }
                //}
            });
        }

        private bool GetPhoto()
        {
            if (!string.IsNullOrEmpty(_appInfo.ZZZPPATH) && File.Exists(_appInfo.ZZZPPATH))
            {
                Log.WriteAsync($"制证照片已存在：{_appInfo.ZZZPPATH}");
                return true;
            }
            string photoDir = string.Format("D:\\Photo\\{0}\\{1}", DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
            if (!Directory.Exists(photoDir))
            {
                Directory.CreateDirectory(photoDir);
            }
            string photoLocalPath = string.Format("{0}\\{1}.jpg", photoDir, _sfz.SFZH);
            string photoRemotePath = string.Format("\\{0}\\{1}\\{2}.jpg", DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"), _sfz.SFZH);
            string err = "";
            try
            {
                //通过FTP下载照片
                FtpDownload ftp = new FtpDownload();
                if (ftp.DownloadFile(photoLocalPath, photoRemotePath, out err))
                {
                    _appInfo.ZZZPPATH = photoLocalPath;
                    return true;
                }
                else
                {
                    Log.WriteAsync(err);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
                return false;
            }
        }
        private void QueryPeopleInfo()
        {
            Log.WriteAsync("开始查询人口信息");
            JObject args = new JObject();
            args["SFZH"] = _sfz.SFZH;
            args["XM"] = _sfz.Name;
            args["CSRQ"] = _sfz.BirthDate;
            args["XB"] = _sfz.Sex;
            args["HasReadIDCard"] = _sfz.IsManualInputNumberVerify;
            if (!_webAccess.Inited)
            {
                if (!_webAccess.Login())
                {
                    Log.WriteAsync($"登录失败：{_webAccess.ErrorMessage}");
                    OnQueryFailed(_webAccess.ErrorMessage);
                    return;
                }
            }

            if (_webAccess.QueryApplyInfo(_sfz.SFZH, out _appInfo))
            {
                Log.WriteAsync($"查询受理信息成功");
                //return;
            }

            PeopleQueryResult result = _webAccess.QueryPeopleInfo(args.ToString());
            if (!Process.IsRunning)
            {
                Log.WriteAsync("流程已结束");
                OnQueryFailed("流程已结束");
                return;
            }
            if (!result.Success)
            {
                Log.WriteAsync($"查询失败：{_webAccess.ErrorMessage}");
                OnQueryFailed(_webAccess.ErrorMessage);
                return;
            }
            QueryPaperInfo();
            UpdatePeopleInfo(result);          
            StopCountdown();
            OnQueryCompleted();
            return;
        }

        private void QueryPaperInfo()
        {
            Log.WriteAsync("开始查询证件信息");
            QueryPaperInfo result = _webAccess.QueryPaperInfo(_sfz.SFZH);
            if (result != null)
            {
                Log.WriteAsync("查询证件信息成功");
                UpdatePaperInfo(result);
            }
            else
            {
                Log.WriteAsync("查询证件信息失败");
            }
            //result = _webAccess.QueryQGPaperInfo(_sfz.SFZH);
            //if (result.Success)
            //{
            //    Log.WriteAsync("查询全国有证件信息可更新");
            //    UpdatePaperInfo(result);
            //    return;
            //}
            //else
            //{
            //    Log.WriteAsync("查询全国无证件信息可更新");
            //}
        }

        private void UpdatePaperInfo(QueryPaperInfo result)
        {
            PaperInfo paperInfo = result.HZ;
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {

                if (!string.IsNullOrEmpty(_appInfo.HZSQ.ZJYXQZ))  //说明已经赋过值了
                {
                    if (int.Parse(_appInfo.HZSQ.ZJYXQZ) < int.Parse(paperInfo.zjyxqz))  //之前赋值的有效期比后来的早，说明后来的证件信息更新
                    {
                        _appInfo.HZSQ.ZJHM = paperInfo.zjhm;
                        _appInfo.HZSQ.ZJYXQZ = paperInfo.zjyxqz;
                        _appInfo.HZSQ.PaperStatus = paperInfo.zjzt;

                        Log.WriteAsync(string.Format("HZ 信息更新: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                    }
                }
                else
                {
                    _appInfo.HZSQ.ZJHM = paperInfo.zjhm;
                    _appInfo.HZSQ.ZJYXQZ = paperInfo.zjyxqz;
                    _appInfo.HZSQ.PaperStatus = paperInfo.zjzt;
                    Log.WriteAsync(string.Format("HZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                }

            }

            paperInfo = result.SCZ;
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {

                if (!string.IsNullOrEmpty(_appInfo.SCZSQ.ZJYXQZ))  //说明已经赋过值了
                {
                    if (int.Parse(_appInfo.SCZSQ.ZJYXQZ) < int.Parse(paperInfo.zjyxqz))  //之前赋值的有效期比后来的早，说明后来的证件信息更新
                    {
                        _appInfo.SCZSQ.ZJHM = paperInfo.zjhm;
                        _appInfo.SCZSQ.ZJYXQZ = paperInfo.zjyxqz;
                        _appInfo.SCZSQ.PaperStatus = paperInfo.zjzt;

                        Log.WriteAsync(string.Format("SCZ 信息更新: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                    }
                }
                else
                {
                    _appInfo.SCZSQ.ZJHM = paperInfo.zjhm;
                    _appInfo.SCZSQ.ZJYXQZ = paperInfo.zjyxqz;
                    _appInfo.SCZSQ.PaperStatus = paperInfo.zjzt;
                    Log.WriteAsync(string.Format("SCZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                }

            }

            paperInfo = result.DLZ;
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {

                if (!string.IsNullOrEmpty(_appInfo.DLZSQ.ZJYXQZ))  //说明已经赋过值了
                {
                    if (int.Parse(_appInfo.DLZSQ.ZJYXQZ) < int.Parse(paperInfo.zjyxqz))  //之前赋值的有效期比后来的早，说明后来的证件信息更新
                    {
                        _appInfo.DLZSQ.ZJHM = paperInfo.zjhm;
                        _appInfo.DLZSQ.ZJYXQZ = paperInfo.zjyxqz;
                        _appInfo.DLZSQ.PaperStatus = paperInfo.zjzt;

                        Log.WriteAsync(string.Format("DLZ 信息更新: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                    }
                }
                else
                {
                    _appInfo.DLZSQ.ZJHM = paperInfo.zjhm;
                    _appInfo.DLZSQ.ZJYXQZ = paperInfo.zjyxqz;
                    _appInfo.DLZSQ.PaperStatus = paperInfo.zjzt;
                    Log.WriteAsync(string.Format("DLZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                }

            }
        }

        private void UpdatePeopleInfo(PeopleQueryResult result)
        {
            try
            {
                Log.WriteAsync($"Update people info from query result...xml path:{BaseDirectory}");
                QGRKInfo qgrkInfo = result.PersonInfo;
                CodeMapService service = CodeMapService.Instance;
                if (_appInfo == null)
                {
                    _appInfo = new PreApplyInfo();
                }
                Log.WriteAsync($"人口信息:{JsonHandler.ConvertToJsonString(qgrkInfo)}");
                _appInfo.SFZH = qgrkInfo.SFZH;
                _appInfo.XB.Code = qgrkInfo.XB_CODE;
                _appInfo.XB.Value = qgrkInfo.XB;
                _appInfo.YJDZ = qgrkInfo.ZZXZ;
                _appInfo.MZ.Code = qgrkInfo.MZ_CODE;
                _appInfo.MZ.Value = qgrkInfo.MZ;
                _appInfo.ZWXM = qgrkInfo.XM;
                _appInfo.CSRQ = qgrkInfo.CSRQ;
                _appInfo.BSWS = qgrkInfo.SNSW;
                _appInfo.CSD.Code = qgrkInfo.CSD_CODE;
                if (qgrkInfo.CSD_CODE.Length >= 2)
                    _appInfo.CSD.Value = Data2Xml.XmlDicReader(BaseDirectory + "//EECMISWS//DICTable//DIC_PM_BIRTHPLACE.xml", qgrkInfo.CSD_CODE.Substring(0, 2));  //出生地只精确到省
                else
                    _appInfo.CSD.Value = qgrkInfo.CSD;


                _appInfo.HKSZD.Code = qgrkInfo.HKSZD_CODE;
                //_appInfo.HKSZD.Value = qgrkInfo.HKSZD;
                if (string.IsNullOrEmpty(qgrkInfo.HKSZD) && qgrkInfo.HKSZD_CODE.Length > 0)
                    _appInfo.HKSZD.Value = Data2Xml.XmlDicReader(BaseDirectory + "//EECMISWS//DICTable//DIC_CITY.xml", qgrkInfo.HKSZD_CODE);
                else
                    _appInfo.HKSZD.Value = qgrkInfo.HKSZD;

                if (!string.IsNullOrEmpty(qgrkInfo.XPDZ) && File.Exists(qgrkInfo.XPDZ))
                {
                    _appInfo.ZZZPPATH = qgrkInfo.XPDZ;
                }

                //不填写邮寄地址的，默认勾选受理点领取
                if (!_config.WorkFlow.ReceiveWay)
                {
                    _appInfo.QZFS = new CodeMap("01", "受理点领取");
                }

                _sfz.Address = qgrkInfo.ZZXZ;
                _sfz.BirthDate = qgrkInfo.CSRQ;
                _sfz.Name = qgrkInfo.XM;
                _sfz.Nation = qgrkInfo.MZ;
                _sfz.Nation_Code = qgrkInfo.MZ_CODE;
                _sfz.Sex = qgrkInfo.XB;
                _sfz.Sex_Code = qgrkInfo.XB_CODE;
                _sfz.SFZH = qgrkInfo.SFZH;

                //if (_sfz.IsManualInputNumberVerify || !File.Exists(_sfz.HeaderPicturePath))
                //{
                _sfz.HeaderPicturePath = qgrkInfo.XPDZ;
                //}
                Log.WriteAsync($"apply info:{JsonHandler.ConvertToJsonString(_appInfo)}");
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }

        }

        private void OnQueryCompleted()
        {
            if (_bCancellFlag || !Process.IsRunning)
            {
                Log.WriteAsync("程序流程已结束");
                return;
            }
            _queryResult = true;
            Log.WriteAsync("人口信息查询成功");
            Action handler = () =>
            {
                SetTips("人口信息查询成功");                
            };
            this.Invoke(handler);
            UpdateData();
            Process.ToNext();
        }

        private void OnQueryFailed(string outParams)
        {
            if (_bCancellFlag || !Process.IsRunning)
            {
                return;
            }
            string msg = string.Format("人口信息查询失败: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                pictureBox1.Image = imgQueryFailed;
                SetTips(msg, false);
                CountdownSecond = 5;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }

        private bool CheckGoNext()
        {
            if (_bCancellFlag)
            {
                return false;
            }
            DialogResult res = GetUserSelection();
            if (res == DialogResult.Yes)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private DialogResult GetUserSelection()
        {
            if (this.InvokeRequired)
            {
                Func<DialogResult> handler = new Func<DialogResult>(GetUserSelection);
                return (DialogResult)this.Invoke(handler);
            }
            string msg = $"查询不到照片，请确认是否已经拍摄了证件照片。" +
                $"\n如果还没有拍摄证件照，请点击\"否\"，并到自助照相机上拍照后再填表; " +
                $"\n如果已经有工作人员认可的照片，请点击\"是\"继续填表.";
            Log.WriteAsync(msg);
            DialogResult res = MessageBox.Show(msg, "操作提示", MessageBoxButtons.YesNoCancel);
            SetTips(msg, false);
            return res;
        }
    }
}
